package com.jn.erp.web.api.institution.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jn.erp.common.core.result.AjaxResult;
import com.jn.erp.common.exception.ServiceException;
import com.jn.erp.common.utils.StringUtils;
import com.jn.erp.security.entity.SysRole;
import com.jn.erp.security.entity.SysUser;
import com.jn.erp.security.entity.SysUserRole;
import com.jn.erp.security.sysservice.SysUserRoleService;
import com.jn.erp.security.sysservice.SysUserService;
import com.jn.erp.security.utils.SecurityUtils;
import com.jn.erp.web.api.institution.entity.vo.EmployeeInfoDto;
import com.jn.erp.web.api.institution.entity.vo.EmployeeStudentDto;
import com.jn.erp.web.api.institution.entity.vo.EmployeeVo;
import com.jn.erp.web.api.institution.mapper.EmployeeMapper;
import com.jn.erp.web.api.institution.service.EmployeeService;
import com.jn.erp.web.api.student.entity.Student;
import com.jn.erp.web.api.student.entity.StudentClass;
import com.jn.erp.web.api.student.service.StudentClassService;
import com.jn.erp.web.api.student.service.StudentService;
import com.jn.erp.web.api.sys.entity.SysOrgUser;
import com.jn.erp.web.api.sys.service.SysOrgUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/9/2 9:41
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;


    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentClassService studentClassService;


    @Override
    public List<EmployeeVo> selectEmployeeList(EmployeeVo employeeVo) {
        return employeeMapper.selectEmployeeList(employeeVo);
    }

    @Override
    public List<EmployeeVo> selectTeacherEmployees(EmployeeVo employeeVo) {
        return employeeMapper.selectTeacherEmployees(employeeVo);
    }

    @Override
    public boolean existOtherOrg(EmployeeVo employeeVo) {
        return employeeMapper.existOtherOrg(employeeVo)>0;
    }

    @Override
    public List<SysRole> employeeRoleList(SysRole sysRole) {
        return employeeMapper.employeeRoleList(sysRole);
    }

    @Override
    public List<EmployeeVo> roleUserList(SysRole sysRole) {
        return employeeMapper.roleUserList(sysRole);
    }

    @Override
    public List<EmployeeStudentDto> getTeacherStudentList(EmployeeVo employeeVo) {

        return employeeMapper.getTeacherStudentList(employeeVo);
    }

    @Override
    public List<EmployeeInfoDto> getTeacherClassList(EmployeeVo employeeVo) {
        return employeeMapper.getTeacherClassList(employeeVo);
    }


    //---------------------------统一pc和小程序接口-----------------------------------------------
    @Autowired
    private SysOrgUserService sysOrgUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysUserService sysUserService;

    //统一新增
    @Override
    public AjaxResult employeeUnifyAdd(EmployeeVo employeeVo) {
        SysUser user = new SysUser();
        BeanUtil.copyProperties(employeeVo, user);
        if (StrUtil.isNotBlank(employeeVo.getRoleIds())) {
            long[] longs = StrUtil.splitToLong(employeeVo.getRoleIds(), ",");
            Long[] Longids = new Long[longs.length];
            int i = 0;
            for (long temp : longs) {
                Longids[i++] = temp;
            }
            user.setRoleIds(Longids);
        }
        //判断手机账号是否存在
         if (StringUtils.isNotEmpty(user.getMobile()) && !sysUserService.checkPhoneUnique(user)) {
//            return AjaxResult.error("新增用户'" + user.getName() + "'失败，手机号码已存在");
             QueryWrapper<SysUser> qu = new QueryWrapper<>();
             qu.eq("mobile", employeeVo.getMobile());
             SysUser one = sysUserService.getOne(qu);

             //本机构下重复手机号判断
             SysOrgUser orgUserOld = getMyOrgUser(user.getOrgId(), user.getMobile());

             //其他机构存在。本机构不存在
             if (orgUserOld == null) {
                 SysOrgUser sysOrgUser = new SysOrgUser();
                 sysOrgUser.setOrgId(user.getOrgId());
                 sysOrgUser.setUserId(one.getId());
                 sysOrgUser.setNickName(employeeVo.getNickName());
                 sysOrgUser.setIsTeach(employeeVo.getIsTeach());
                 sysOrgUser.setIsJob(employeeVo.getIsJob());
                 sysOrgUser.setDeleted(0);
                 sysOrgUserService.save(sysOrgUser);
                 if (user.getRoleIds().length > 0) {
                     sysUserRoleService.insertUserRole(one.getId(), user.getRoleIds(), employeeVo.getOrgId());
                 }
                 return AjaxResult.success("手机号创建的用户已在其他机构存在，已为账号为【" + one.getName() + "】添加进该机构！");
             } else {
                 //本机构下存在
                 if (orgUserOld.getDeleted() == 1) {
                     orgUserOld.setDeleted(0);
                     orgUserOld.setNickName(employeeVo.getNickName());
                     orgUserOld.setIsTeach(employeeVo.getIsTeach());
                     orgUserOld.setIsJob(employeeVo.getIsJob());
                     sysOrgUserService.updateById(orgUserOld);
                     if (user.getRoleIds().length > 0) {
                         sysUserRoleService.insertUserRole(orgUserOld.getUserId(), user.getRoleIds(), employeeVo.getOrgId());
                     }
                     return AjaxResult.success("手机号创建的员工在本机构中存在过，已对账号为【" + one.getName() + "】更新状态！");
                 }
                 if (orgUserOld.getDeleted() == 0) {
                     return AjaxResult.error("新建用户手机号已在该机构中存在在职员工");
                 }
             }
         }
        if (!sysUserService.checkUserNameUnique(user)) {
            return AjaxResult.error("新增用户'" + user.getName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !sysUserService.checkEmailUnique(user)) {
            return AjaxResult.error("新增用户'" + user.getName() + "'失败，邮箱账号已存在");
        }
        //初始密码为123456
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        user.setAddTime(LocalDateTime.now());
        user.setState(false);
        sysUserService.save(user);
        SysOrgUser sysOrgUser = new SysOrgUser();
        sysOrgUser.setOrgId(user.getOrgId());
        sysOrgUser.setUserId(user.getId());
        sysOrgUser.setNickName(employeeVo.getNickName());
        sysOrgUser.setIsTeach(employeeVo.getIsTeach());
        sysOrgUser.setIsJob(employeeVo.getIsJob());
        sysOrgUserService.save(sysOrgUser);
        if (user.getRoleIds().length > 0) {
            sysUserRoleService.insertUserRole(user.getId(), user.getRoleIds(),employeeVo.getOrgId());
        }
        return AjaxResult.success();
    }

    //获取本机构下的用户SysOrgUser
    private SysOrgUser getMyOrgUser(Long orgId,String mobile){
        QueryWrapper<SysUser> qu=new QueryWrapper<>();
        qu.eq("mobile",mobile);
        SysUser one = sysUserService.getOne(qu);

        QueryWrapper<SysOrgUser> qou=new QueryWrapper<>();
        qou.eq("org_id",orgId);
        qou.eq("user_id",one.getId());
        SysOrgUser orgUserOld = sysOrgUserService.getOne(qou);
        return orgUserOld;
    }

    //统一修改
    @Override
    public AjaxResult employeeUnifyEdit(EmployeeVo employeeVo) {
        //判断是否更改员工离职状态
        if(!employeeVo.getIsJob()){
            //如果离职 并且填写好交接
            if(employeeVo.getConvert()!=null){
                UpdateWrapper<Student> qwCounselor=new UpdateWrapper<>();
                qwCounselor.set("counselor_id",employeeVo.getConvert().get("counselorId"));
                qwCounselor.eq("counselor_id",employeeVo.getId());
                qwCounselor.eq("deleted","0");   //不是删除
                qwCounselor.ne("stage",5);       //不是历史
                qwCounselor.eq("org_id",employeeVo.getOrgId()); //员工所在机构
                studentService.update(qwCounselor);

                UpdateWrapper<Student> qwManagement=new UpdateWrapper<>();
                qwManagement.set("management_id",employeeVo.getConvert().get("managementId"));
                qwManagement.eq("management_id",employeeVo.getId());
                qwManagement.eq("deleted","0");   //不是删除
                qwManagement.ne("stage",5);       //不是历史
                qwManagement.eq("org_id",employeeVo.getOrgId()); //员工所在机构
                studentService.update(qwManagement);

                UpdateWrapper<StudentClass> qwClass=new UpdateWrapper<>();
                qwClass.set("teacher_id",employeeVo.getConvert().get("teacherId"));
                qwClass.eq("teacher_id",employeeVo.getId());
                qwClass.eq("org_id",employeeVo.getOrgId());
                qwClass.eq("deleted","0");
                studentClassService.update(qwClass);
            }
            if(!employeeUnifyExistStudent(employeeVo)){
                    return AjaxResult.success(false);
            }
            UpdateWrapper<SysOrgUser> up=new UpdateWrapper<>();
            up.set("is_job",employeeVo.getIsJob());
            up.eq("user_id",employeeVo.getId());
            up.eq("org_id",employeeVo.getOrgId());
            sysOrgUserService.update(up);
            return AjaxResult.success(true);
        }
        SysUser user = new SysUser();
        BeanUtil.copyProperties(employeeVo, user);
        if (StrUtil.isNotBlank(employeeVo.getRoleIds())) {
            long[] longs = StrUtil.splitToLong(employeeVo.getRoleIds(), ",");
            Long[] Longids = new Long[longs.length];
            int i = 0;
            for (long temp : longs) {
                Longids[i++] = temp;
            }
            user.setRoleIds(Longids);
        }
        if (user.getId() != null && 1L == user.getId()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
        if (!sysUserService.checkUserNameUnique(user)) {
            return AjaxResult.error("修改用户'" + user.getName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getMobile()) && !sysUserService.checkPhoneUnique(user)) {
            return AjaxResult.error("修改用户'" + user.getName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !sysUserService.checkEmailUnique(user)) {
            return AjaxResult.error("修改用户'" + user.getName() + "'失败，邮箱账号已存在");
        }
        Long userId = user.getId();

        //删除机构用户角色
        deleteUnifyRolesOrg(employeeVo.getOrgId(), userId);
        // 新增用户与角色管理
        sysUserRoleService.insertUserRole(userId, user.getRoleIds(), employeeVo.getOrgId());
        sysUserService.updateById(user);
        UpdateWrapper<SysOrgUser> up=new UpdateWrapper<>();
        up.set("nick_name",employeeVo.getNickName());
        up.set("is_teach",employeeVo.getIsTeach());
        up.set("is_job",employeeVo.getIsJob());
        up.eq("user_id",user.getId());
        up.eq("org_id",user.getOrgId());
        sysOrgUserService.update(up);
        return AjaxResult.success(true);
    }

    //判断是否存在跟进 学管 班级
    @Override
    public Boolean employeeUnifyExistStudent(EmployeeVo employeeVo) {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //跟进人                                                        //学管师
        qw.eq("counselor_id",employeeVo.getId()).or().eq("management_id",employeeVo.getId());
        qw.eq("deleted","0");   //不是删除
        qw.ne("stage",5);       //不是历史
        qw.eq("org_id",employeeVo.getOrgId()); //员工所在机构
        List<Student> list = studentService.list(qw);
        QueryWrapper<StudentClass> qwc=new QueryWrapper<>();
        qwc.eq("teacher_id",employeeVo.getId());
        qwc.eq("org_id",employeeVo.getOrgId());
        qwc.eq("deleted","0");
        List<StudentClass> list1 = studentClassService.list(qwc);
        if(list.size()==0&&list1.size()==0){
            return true;
        }else {
            return false;
        }

    }


    //统一获取员工信息
    @Override
    public AjaxResult employeeUnifyGetInfo(EmployeeVo employeeVo) {
        //        sysUserService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        Long orgId = employeeVo.getOrgId();
        Long userId=employeeVo.getId();

        SysRole sysRole = new SysRole();
        sysRole.setOrgId(orgId);
        List<SysRole> roles = this.employeeRoleList(sysRole);
        ajax.put("roles", roles);
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = sysUserService.getById(userId);
            EmployeeVo employee = new EmployeeVo();
            BeanUtil.copyProperties(sysUser, employee);
            QueryWrapper<SysOrgUser> qwou = new QueryWrapper<>();
            qwou.eq("org_id", orgId);
            qwou.eq("user_id", sysUser.getId());
            SysOrgUser orgUser = sysOrgUserService.getOne(qwou);
            employee.setNickName(orgUser.getNickName());
            employee.setIsTeach(orgUser.getIsTeach());
            employee.setIsJob(orgUser.getIsJob());
            ajax.put(AjaxResult.DATA_TAG, employee);
            QueryWrapper<SysUserRole> qw = new QueryWrapper<>();
            qw.eq("user_id", sysUser.getId());
            qw.eq("org_id", orgId);
            List<SysUserRole> list = sysUserRoleService.list(qw);
            ajax.put("roleIds", list.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }


    //用于删除用户在该机构下的所有角色方法
    public void deleteUnifyRolesOrg(Object orgId, Object userId) {
        QueryWrapper<SysUserRole> qwd = new QueryWrapper<>();
        qwd.eq("user_id", userId);
        qwd.eq("org_id", orgId);
        sysUserRoleService.remove(qwd);
    }

    @Override
    public List<EmployeeVo> selectUnifyListStaff(EmployeeVo employeeVo) {
        return employeeMapper.selectUnifyListStaff(employeeVo);
    }

    @Override
    public List<EmployeeVo> followPeopleList(EmployeeVo employeeVo) {
        return employeeMapper.followPeopleList(employeeVo);
    }

    @Override
    public List<EmployeeVo> managerList(EmployeeVo employeeVo) {
        return employeeMapper.managerList(employeeVo);
    }

    @Override
    public List<EmployeeVo> teacherList(EmployeeVo employeeVo) {
        return employeeMapper.teacherList(employeeVo);
    }

    @Override
    public List<EmployeeVo> managerJobList(EmployeeVo employeeVo) {
        return employeeMapper.managerJobList(employeeVo);
    }

    @Override
    public List<EmployeeVo> peopleJobList(EmployeeVo employeeVo) {


        return employeeMapper.peopleJobList(employeeVo);
    }

    @Override
    public List<EmployeeVo> performanceList(EmployeeVo employeeVo) {
        return employeeMapper.performanceList(employeeVo);
    }
}
